<template>
    <div class="home" :style="{ backgroundImage: `url(${bgUrl})` }">
        <!-- Top-left avatar -->
        <div class="avatar-wrap" @click="goToProfile">
            <img class="avatar" :src="avatarUrl" alt="avatar" />
        </div>

        <!-- Center title -->
        <div class="title">Rugged</div>

        <!-- Action cards (fixed above bottom dock) -->
        <div class="cards">
            <button class="card" type="button" @click="onLearn">
                <div class="card-title">Learn</div>
                <div class="card-count">{{ stats.learn }}</div>
            </button>

            <button class="card" type="button" @click="onReview">
                <div class="card-title">Review</div>
                <div class="card-count">{{ stats.review }}</div>
            </button>
        </div>

        <!-- Bottom dock icons -->
        <div class="dock">
            <button class="dock-btn left" aria-label="more-settings" @click="goToMoreSettings">
                <!-- Settings/Wrench icon -->
                <svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.07-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.22-0.37-0.29-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.47,0.41L9.25,5.35C8.66,5.59,8.12,5.92,7.63,6.29L5.24,5.33c-0.22-0.08-0.47,0-0.59,0.22L2.74,8.87 C2.62,9.08,2.66,9.34,2.86,9.48l2.03,1.58C4.84,11.36,4.82,11.69,4.82,12s0.02,0.64,0.07,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.22,0.37,0.29,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.36,2.54 c0.05,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.44-0.17,0.47-0.41l0.36-2.54c0.59-0.24,1.13-0.56,1.62-0.94l2.39,0.96 c0.22,0.08,0.47,0,0.59-0.22l1.92-3.32c0.12-0.22,0.07-0.47-0.12-0.61L19.14,12.94z M12,15.6c-1.98,0-3.6-1.62-3.6-3.6 s1.62-3.6,3.6-3.6s3.6,1.62,3.6,3.6S13.98,15.6,12,15.6z"/></svg>
            </button>
            <button class="dock-btn center" aria-label="trash" @click="goToStudy">
                <!-- Trash icon -->
                <svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M9 3h6l1 2h4v2H4V5h4l1-2zm1 6h2v10h-2V9zm4 0h2v10h-2V9z"/></svg>
            </button>
            <button class="dock-btn right" aria-label="gallery" @click="goDashboard">
                <!-- Image icon -->
                <svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M21 19V5H3v14h18zM5 7h14v8l-4-4-3 3-2-2-5 5V7z"/></svg>
            </button>
        </div>

        <!-- Toast Notification -->
        <div class="toast" v-if="toastMessage" :class="toastType">
            {{ toastMessage }}
        </div>
    </div>
    
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { bgUrl } from '@/config/background.js'
import { getToken } from '@/utils/auth.js'

const stats = reactive({
    learn: 0,
    review: 0,
})

const avatarUrl = './avatar.jpg'
const router = useRouter()
const toastMessage = ref('')
const toastType = ref('success')
const isLoading = ref(false)

function showToast(message, type = 'success') {
    toastMessage.value = message
    toastType.value = type
    setTimeout(() => {
        toastMessage.value = ''
    }, 3000)
}

// 获取统计数据
async function fetchStats() {
    isLoading.value = true
    try {
        const token = getToken()
        console.log('=== 开始获取统计数据 ===')
        console.log('Token状态:', token ? `存在 (${token.substring(0, 10)}...)` : '不存在')
        console.log('localStorage token:', localStorage.getItem('token'))
        
        const headers = {
            'Content-Type': 'application/json',
        }
        
        // 尝试多种token传递方式
        if (token) {
            // 方式1: Bearer token (标准方式)
            headers['Authorization'] = `Bearer ${token}`
            // 方式2: 直接传递token (有些后端可能需要)
            // headers['token'] = token
            // 方式3: X-Auth-Token (另一种常见方式)
            // headers['X-Auth-Token'] = token
            console.log('已添加Authorization头: Bearer', token.substring(0, 10) + '...')
        }

        console.log('请求URL: /api/study/stats (将通过代理转发)')
        console.log('请求头:', JSON.stringify(headers, null, 2))

        const response = await fetch('/api/study/stats', {
            method: 'GET',
            headers: headers,
        })

        console.log('响应状态:', response.status, response.statusText)
        console.log('响应头:', Object.fromEntries(response.headers.entries()))

        if (!response.ok) {
            let errorText = ''
            try {
                errorText = await response.text()
                console.error('API响应错误内容:', errorText)
            } catch (e) {
                console.error('无法读取错误响应')
            }
            throw new Error(`HTTP error! status: ${response.status}, message: ${errorText || response.statusText}`)
        }

        const result = await response.json()
        console.log('=== 完整响应数据 ===')
        console.log(JSON.stringify(result, null, 2))
        console.log('响应数据类型:', typeof result)
        console.log('响应是否为数组:', Array.isArray(result))
        
        // 根据后端返回的数据结构更新统计
        let foundData = false
        
        // 方式1: result.data.remainingWordsToLearn
        if (result.data && typeof result.data === 'object') {
            console.log('✓ 找到 result.data 对象')
            if ('remainingWordsToLearn' in result.data || 'todayReviewCount' in result.data) {
                stats.learn = result.data.remainingWordsToLearn ?? 0
                stats.review = result.data.todayReviewCount ?? 0
                foundData = true
                console.log('✓ 从 result.data 读取成功:', {
                    remainingWordsToLearn: result.data.remainingWordsToLearn,
                    todayReviewCount: result.data.todayReviewCount,
                    最终值: { learn: stats.learn, review: stats.review }
                })
            }
        }
        
        // 方式2: result.remainingWordsToLearn (直接字段)
        if (!foundData && ('remainingWordsToLearn' in result || 'todayReviewCount' in result)) {
            console.log('✓ 找到 result 直接字段')
            stats.learn = result.remainingWordsToLearn ?? 0
            stats.review = result.todayReviewCount ?? 0
            foundData = true
            console.log('✓ 从 result 直接读取成功:', {
                remainingWordsToLearn: result.remainingWordsToLearn,
                todayReviewCount: result.todayReviewCount,
                最终值: { learn: stats.learn, review: stats.review }
            })
        }
        
        // 方式3: 尝试深度查找
        if (!foundData) {
            console.warn('⚠ 无法识别标准数据结构，尝试深度查找...')
            const findValue = (obj, keys) => {
                for (const key of keys) {
                    if (obj && typeof obj === 'object' && key in obj) {
                        return obj[key]
                    }
                }
                return null
            }
            
            const learnValue = findValue(result, ['remainingWordsToLearn', 'remaining', 'learn', 'toLearn'])
            const reviewValue = findValue(result, ['todayReviewCount', 'review', 'todayReview', 'reviewCount'])
            
            if (learnValue !== null || reviewValue !== null) {
                stats.learn = learnValue ?? 0
                stats.review = reviewValue ?? 0
                foundData = true
                console.log('✓ 深度查找成功:', { learn: stats.learn, review: stats.review })
            } else {
                console.error('✗ 无法找到数据字段')
                console.log('响应对象的所有键:', Object.keys(result))
                if (result.data) {
                    console.log('result.data的所有键:', Object.keys(result.data))
                }
            }
        }
        
        if (!foundData) {
            console.error('✗ 无法解析数据，请检查后端返回的数据结构')
            showToast('数据格式异常，请查看控制台', 'error')
        } else {
            console.log('=== 最终统计数据 ===', {
                learn: stats.learn,
                review: stats.review
            })
        }
    } catch (error) {
        console.error('=== 获取统计数据失败 ===')
        console.error('错误类型:', error.constructor.name)
        console.error('错误消息:', error.message)
        console.error('错误堆栈:', error.stack)
        showToast('获取统计数据失败: ' + error.message, 'error')
    } finally {
        isLoading.value = false
        console.log('=== 请求结束 ===')
    }
}

onMounted(() => {
    // 检查是否需要显示登录成功提示
    if (sessionStorage.getItem('showLoginSuccess') === 'true') {
        showToast('登录成功！', 'success')
        sessionStorage.removeItem('showLoginSuccess')
    }
    
    // 获取统计数据
    fetchStats()
})

function onLearn() { 
    const root = document.querySelector('.home')
    if (!root) { router.push('/learn'); return }
    root.classList.add('zoom-fade')
    setTimeout(() => router.push('/learn'), 380)
}

function onReview() { 
    const root = document.querySelector('.home')
    if (!root) { router.push('/review'); return }
    root.classList.add('zoom-fade')
    setTimeout(() => router.push('/review'), 380)
}

function noop() {}

function goDashboard() {
    const root = document.querySelector('.home')
    if (!root) {
        router.push('/dashboard')
        return
    }
    root.classList.add('leaving-up')
    setTimeout(() => router.push('/dashboard'), 320)
}

function goToStudy() {
    // 跳转到学习页面
    onLearn()
}

function goToProfile() {
    const root = document.querySelector('.home')
    if (!root) {
        router.push('/profile')
        return
    }
    // 使用缩放淡出动画
    root.classList.add('zoom-fade')
    setTimeout(() => router.push('/profile'), 380)
}

function goToMoreSettings() {
    const root = document.querySelector('.home')
    if (!root) {
        router.push('/more-settings')
        return
    }
    // 使用向上滑出动画
    root.classList.add('leaving-up')
    setTimeout(() => router.push('/more-settings'), 320)
}
</script>

<style scoped>
/* Layout */
.home {
    position: fixed; /* lock page and background */
    inset: 0; /* top:0; right:0; bottom:0; left:0 */
    overflow: hidden;
    width: 100vw;
    height: 100vh;
    color: #ffffff;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
}

.leaving-up { transform: translateY(-100vh); opacity: 0; transition: transform .32s ease, opacity .32s ease; }

.zoom-fade { transform: scale(1.15); opacity: 0; filter: blur(10px); transition: transform .38s cubic-bezier(0.4, 0, 0.2, 1), opacity .38s ease, filter .38s ease; }

/* Subtle dark overlay using backdrop on children via glassmorphism cards */
.avatar-wrap {
    position: absolute;
    top: 18px;
    left: 38px; /* move a bit to the right */
    cursor: pointer;
    transition: transform 0.2s ease;
}

.avatar-wrap:hover {
    transform: scale(1.05);
}

.avatar-wrap:active {
    transform: scale(0.95);
}

.avatar {
    width: 60px; /* diameter for radius 30px */
    height: 60px;
    border-radius: 50%;
    object-fit: cover;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);
}

.title {
    margin-top: 120px;
    font-size: 45px;
    font-weight: 700;
    text-align: center;
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.55);
}

.cards {
    position: fixed;
    left: 60px; /* page side margin */
    right: 60px; /* page side margin */
    bottom: 150px; /* further above dock per feedback */
    display: flex;
    flex-direction: row; /* same line */
    justify-content: center;
    gap: 25px; /* distance between two cards */
}

.card {
    appearance: none;
    border: none;
    cursor: pointer;
    text-align: left;
    padding: 18px 24px;
    border-radius: 16px;
    color: #fff;
    background: rgba(40, 40, 45, 0.55);
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45), inset 0 0 0 1px rgba(255, 255, 255, 0.06);
    transition: transform 0.2s ease, background 0.2s ease, box-shadow 0.2s ease;
    /* responsive width: slightly smaller than 692, honor 60px margins and 25px gap */
    width: clamp(320px, calc((100vw - 120px - 25px) / 2), 640px);
    height: 100px; /* requested height */
}

.card:hover {
    transform: translateY(-2px);
    background: rgba(55, 55, 62, 0.6);
    box-shadow: 0 14px 36px rgba(0, 0, 0, 0.55), inset 0 0 0 1px rgba(255, 255, 255, 0.08);
}

.card:active {
    transform: translateY(0);
}

.card-title {
    font-size: 23px; /* Learn/Review font size */
    font-weight: 700;
    letter-spacing: 0.3px;
}

.card-count {
    margin-top: 8px;
    font-size: 23px; /* match request */
    color: #ffcc4d;
}

.dock {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 18px;
    height: 36px;
    padding: 0 22px;
}

.dock-btn {
    position: absolute;
    width: 36px;
    height: 36px;
    display: grid;
    place-items: center;
    color: #fff;
    background: transparent; /* fully transparent */
    border: none;
    border-radius: 8px;
}

.dock-btn.left { left: 22px; }
.dock-btn.center { left: 50%; transform: translateX(-50%); }
.dock-btn.right { right: 22px; }

.dock-btn svg {
    width: 28px;
    height: 28px;
    fill: #ffffff;
}

@media (max-width: 720px) {
    .title {
        margin-top: 96px;
        font-size: 45px; /* keep exact per spec */
    }

    .cards { transform: translateX(-50%) scale(0.9); }

    .card-title { font-size: 23px; }
    .card-count { font-size: 23px; }
}

/* Remove default page margins and prevent overscroll to avoid seams/motion */
:global(html, body, #app) {
    margin: 0;
    height: 100%;
    overscroll-behavior: none;
}

/* Toast Styles */
.toast {
    position: fixed;
    top: 60px;
    left: 50%;
    transform: translateX(-50%);
    padding: 14px 24px;
    border-radius: 16px;
    font-size: 15px;
    font-weight: 500;
    color: #ffffff;
    z-index: 10000;
    animation: toastSlideIn 0.5s ease-out;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
    display: flex;
    align-items: center;
    gap: 8px;
    backdrop-filter: blur(20px) saturate(180%);
    -webkit-backdrop-filter: blur(20px) saturate(180%);
    border: 1px solid rgba(255, 255, 255, 0.25);
}

.toast.success {
    background: rgba(16, 185, 129, 0.25);
    box-shadow: 0 8px 32px rgba(16, 185, 129, 0.3);
}

.toast.error {
    background: #ef4444;
}

@keyframes toastSlideIn {
    from {
        transform: translateX(-50%) translateY(-40px);
        opacity: 0;
    }
    to {
        transform: translateX(-50%) translateY(0);
        opacity: 1;
    }
}
</style>



